const chrome = window.chrome
const storage = chrome.storage;
// 监听浏览器标签页的创建和关闭事件
chrome.tabs.onCreated.addListener(updateTabList);
chrome.tabs.onRemoved.addListener(updateTabList);
chrome.tabs.onActivated.addListener(updateTabList);
chrome.tabs.onReplaced.addListener(updateTabList);
chrome.tabs.onUpdated.addListener(updateTabList);
function updateTabList() {
  chrome.tabs.query({ currentWindow: true }, function (tabs) {
    for (let i = 0; i < tabs.length; i++) {
      if (tabs[i].active) {
        let tableid = tabs[i].id
        chrome.tabs.get(tableid, function (tab) {
          // 获取当前活动标签页的详细信息
          let str = 'ruten.com.tw/'
          let url = tab.url == '' ? tab.pendingUrl : tab.url
          if (url.includes(str)) {
            chrome.action.setPopup({ popup: './popup.html' });
          } else {
            chrome.action.setPopup({ popup: '' });
          }
        });
      }

    }
  })

}


chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  if (request.data.action === 'rescookiedataLutinrobot') {
    sendResponse({
      message: "success"
    });
    if (request.data.robotputinnum == 0) {
      chrome.tabs.query({ currentWindow: true, active: true }, (tabs) => {
        saveData(tabs[0].id, 'robotputintabsid')
      })
    }

    lutinrobotPutin(request.data)

  }
});

function lutinrobotPutin(data) {
  loadData('robotputintabsid', function (tabsid) {
    // console.log(data);
    let se_date = getYesterdayAndThirtyDaysAgo()
    // let formData = new URLSearchParams();

    // 添加需要携带的参数到 FormData 对象中
    formData.append('g_nos', data.data);
    formData.append('budget', '999999999');
    formData.append('start_time', se_date.todayFormatted);
    formData.append('end_time', se_date.futureFormatted);
    formData.append('agent_bid_cost', data.offer);
    formData.append('agent_bid_option', 'U');
    formData.append('strategy', 'C');

    fetch(`https://rapi.ruten.com.tw/api/rtb/v1/index.php/${data.user}/agent_group/create`, {
      method: 'post',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
        'Cookie': data.cookies,
        'Referer': `https://promote.ruten.com.tw/rtb/agent_create.php?g_nos=${data.data}`,
        'Origin': 'https://promote.ruten.com.tw'
      },
      body: formData
    }).then(response => response.json()).then(code => {
      // console.log(code);
      if (code.status == "success") {
        sendMessageToTab({ action: 'getcookiedataLutinrobot' });
      } else {
        sendMessageToTab({ action: 'getcookiedataLutinrobotno',data: data.data.length });
      }
    }).catch(error => {
      console.log(error);
      sendMessageToTab({ action: 'getcookiedataLutinrobotno',data: data.data.length });
    });
  })

}

function getYesterdayAndThirtyDaysAgo() {
  let today = new Date();

  // 获取今天的年、月、日
  let year = today.getFullYear();
  let month = today.getMonth() + 1; // 月份是从 0 开始计数的，所以要加 1
  let day = today.getDate();

  // 格式化今天的日期
  let monthString = month < 10 ? '0' + month : month;
  let dayString = day < 10 ? '0' + day : day;
  let todayFormatted = `${year}/${monthString}/${dayString}`;

  // 获取730天后的日期
  let futureDate = new Date(today);
  futureDate.setDate(futureDate.getDate() + 730);

  // 获取730天后的年、月、日
  let futureYear = futureDate.getFullYear();
  let futureMonth = futureDate.getMonth() + 1; // 月份是从 0 开始计数的，所以要加 1
  let futureDay = futureDate.getDate();

  // 格式化730天后的日期
  let futureMonthString = futureMonth < 10 ? '0' + futureMonth : futureMonth;
  let futureDayString = futureDay < 10 ? '0' + futureDay : futureDay;
  let futureFormatted = `${futureYear}/${futureMonthString}/${futureDayString}`;

  let daydate = {
    todayFormatted: todayFormatted,
    futureFormatted: futureFormatted
  };

  return daydate;
}



// 保存数据到chrome.storage
function saveData(data, key) {
  const obj = {};
  obj[key] = data;
  storage.local.set(obj, function () {
    // //console.log('Data saved successfully.');
  });
}


// 读取chrome.storage中的数据
function loadData(key, callback) {
  chrome.storage.local.get([key], function (result) {
    const data = result[key];
    callback(data);
  });
}



function sendMessageToTab(message) {
  loadData('robotputintabsid', function (tabsid) {
    // console.log(tabsid);
    chrome.tabs.sendMessage(tabsid, message);
  })
  
}


